package com.hwg.emp.web.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hwg.emp.common.exception.EmpException;
import com.hwg.emp.model.ModuleMD;
import com.hwg.emp.model.UserMD;
import com.hwg.emp.service.ModuleService;
import com.hwg.emp.service.ServiceFactroy;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class LoadMenuController extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		ModuleService service = ServiceFactroy.getService(ModuleService.class);
		try{
			UserMD user = (UserMD)req.getSession().getAttribute("USER");
			String roleId = user.getRole().getId();
			List<ModuleMD> parentModules = service.getParentModuleByRoleID(roleId);
			Map<String, List<ModuleMD>> modules = new HashMap<>();
			for (int i = 0; i < parentModules.size(); i++) {
				modules.put("parentModule"+i, service.getModuleByParentId(parentModules.get(i).getId()));
			}
			JSONArray jsonArray = new JSONArray();
			for (int i = 0; i < parentModules.size(); i++) {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("id", parentModules.get(i).getId());
				jsonObject.put("text", parentModules.get(i).getName());
				jsonObject.put("state", "closed");
				List<ModuleMD> list = modules.get("parentModule"+i);
				JSONArray array = new JSONArray();
				for(int j = 0;j<list.size();j++){
					JSONObject object = new JSONObject();
					object.put("id", list.get(j).getId());
					object.put("text", list.get(j).getName());
					JSONObject object1 = new JSONObject();
					object1.put("url", list.get(j).getUrl());
					object.put("attributes", object1);
					array.add(object);
				}
				jsonObject.put("children", array);
				jsonArray.add(jsonObject);
			}
			resp.getWriter().write(jsonArray.toString());
		} catch(EmpException e){
			req.setAttribute("message", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			req.setAttribute("message", "系统繁忙,请稍后再试!");
		}
	}
	
}
